import { useEffect, useRef } from 'react'

type IReadyCallback = (instance?: ISMCaptchaInstance) => void
type ISuccessCallback = (data: ISMCaptchaResult) => void
type INoopCallback = () => void

interface IUseCaptchaProps {
  onReady: IReadyCallback
  onSuccess: ISuccessCallback
  onError: INoopCallback
}

interface ISMCaptchaResult {
  rid: string
  pass: boolean
}

export interface ISMCaptchaInstance {
  appendTo(node: string): void
  bindForm(formId: string): void
  getValidate(): ISMCaptchaResult
  getResult(): ISMCaptchaResult
  verify(): void
  reset(): void
  onReady(fn: INoopCallback): void
  onSuccess(fn: ISuccessCallback): void
  onError(fn: (errType: string, errMsg: any) => void): void
  onClose(fn: INoopCallback): void
}

export default function useCaptcha(props: IUseCaptchaProps) {
  const captchaInstance = useRef<ISMCaptchaInstance>()

  function smCaptchaCallback(instance: ISMCaptchaInstance) {
    captchaInstance.current = instance
    instance.onSuccess(data => {
      props.onSuccess(data)
    })
    instance.onReady(() => {
      props.onReady(captchaInstance.current)
    })
    instance.onError((errType: string, errMsg: any) => {
      console.log(`errType: ${errType}, errMsg: ${errMsg}`)
      props.onError()
    })
  }

  useEffect(() => {
    window.initSMCaptcha(
      {
        organization: 'xDpjo6XUA7hRqFdEkWNp',
        product: 'popup',
        width: '400px'
      },
      smCaptchaCallback
    )
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
}
